function [K H r Gamma]=decoup(A,B,C,TF)
%TF是传递函数参数，系数从高次到低次排列，按顺序
%S^2+4S+5, S^2+4S+4 :[1 4 5 1 4 4]
    ctrlb=ctrb(A,B);
    [n m]=size(B);
    if(rank(ctrlb)<n)
        error('System isn''t controllable');
    end
    
    r=zeros(1,m);   %Խ
    for i=1:m
        flag=0;
        for k=0:n-1
            if(rank((C(i,:)*(A^k)*B))>0)
                r(i)=k+1;
                flag=1;
                break
            end
        end
        if(flag==0)
           error('Decoupling is impossible'); 
        end
    end
    
    Gamma=zeros(m,m);   %Ͼ
    for i=1:m
        Gamma(i,:)=C(i,:)*(A^(r(i)-1))*B;
    end
    if(rank(Gamma)<m)
        error('Coupling Matrix is Singular!');
    end
    
    if (length(TF)~=(sum(r)+m))
        error('Transfer Function Input error')
    end
    
    H=inv(Gamma);
    k=zeros(m,n);
    cnt=1;
    for i=1:m
        for j=0:r(i)
            k(i,:)=k(i,:)+C(i,:)*(A^(r(i)-j)).*TF(cnt);
            cnt=cnt+1;
        end
    end
    K=-H*k;
end